package com.dexilaonian.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dexilaonian.R;
import com.dexilaonian.adpter.VolunteerAdapter;
import com.dexilaonian.bean.TopicBean;
import com.dexilaonian.bean.VolunteerBean;
import com.dexilaonian.permission.AfterPermissionGranted;
import com.dexilaonian.permission.PermissionUtils;
import com.dexilaonian.utils.BitmapZip;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.FileUtils;
import com.dexilaonian.utils.ImageLoader;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.view.LoadingDialog;
import com.dexilaonian.view.MultiImageSelectorActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class OnlineVolunteerActivity extends AppCompatActivity {
    private static final int REQUEST_IMAGE = 31;
    private static final int CAMERA_PERIMISSION_CODE = 32;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service3)
    TextView baseTitleService3;
    @Bind(R.id.tv_volunteer_time)
    TextView tvVolunteerTime;
    @Bind(R.id.hh)
    ImageView hh;
    @Bind(R.id.on_voluntee_ask)
    TextView onVolunteeAsk;
    @Bind(R.id.iv_voluneer_ask)
    ImageView ivVoluneerAsk;
    @Bind(R.id.ll_vol_ask)
    LinearLayout llVolAsk;
    @Bind(R.id.recycler_volunteer)
    RecyclerView recyclerVolunteer;
    @Bind(R.id.et_volunteer)
    EditText etVolunteer;
    @Bind(R.id.ll_vv)
    LinearLayout llVv;
    @Bind(R.id.rl_fasong)
    RelativeLayout rlFasong;
    @Bind(R.id.tv_fasong)
    TextView tvFasong;
    @Bind(R.id.iv_fasong)
    ImageView ivFasong;
    @Bind(R.id.ll_tupian)
    LinearLayout llTupian;

    @Bind(R.id.ll_all_photo)
    LinearLayout llAllPhoto;

    private List<VolunteerBean> volunteerlist = new ArrayList<>();
    private List<TopicBean> topicList = new ArrayList<>();

    private int postion = 0;
    private String topicId = "";
    private String imageUrl = "";
    private String avatar = "http://dxyisudai.com/resource/xiaoxiao/images/face/20180629/1530238646813438193.png";
    private String content = "";
    private LoadingDialog dialog;
    private boolean flag = true;
    private int mPostion = 0;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private String get_imageUrl;
    private String fatherId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_volunteer);
        ButterKnife.bind(this);
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        dialog = new LoadingDialog(this);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            topicId = extras.getString("topicId");
            content = extras.getString("content");
            imageUrl = extras.getString("imageUrl");
            if (!TextUtils.isEmpty(content)) {
                onVolunteeAsk.setText(content);
            }
            if (!TextUtils.isEmpty(imageUrl)) {
                ivVoluneerAsk.setVisibility(View.VISIBLE);
                ImageLoader.display(OnlineVolunteerActivity.this, imageUrl, ivVoluneerAsk);
            }
            Log.e("TTTTTTT", topicId + "==" + content + "=" + imageUrl);
        }
      //  InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
     //   imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
        initListener();//监听发送内容变化
        initgetVolunteerList(); //聊天内容列表
    }

    private void initListener() {
        etVolunteer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    ivFasong.setVisibility(View.GONE);
                    tvFasong.setVisibility(View.VISIBLE);
                    mPostion = 1;
                } else {
                    ivFasong.setVisibility(View.VISIBLE);
                    tvFasong.setVisibility(View.GONE);
                    mPostion = 0;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.back, R.id.rl_fasong,R.id.ll_tupian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.ll_tupian:
                camera();
                break;
            case R.id.rl_fasong:
                if (mPostion != 0) {
                    initBack("");
                } else {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                  //  imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);  //显示软键盘
                 //   imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
                    flag = ! flag;
                    if (!flag) {
                        view.clearAnimation();
                        llAllPhoto.setVisibility(View.VISIBLE);
                        ivFasong.setImageDrawable(getDrawable(R.drawable.guanbix));
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘

                    } else {
                       // etVolunteer.requestFocus();
                        llAllPhoto.setVisibility(View.GONE);
                        ivFasong.setImageDrawable(getDrawable(R.drawable.shangchuan));
                        imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);  //显示软键盘
                    }
                }
                break;
        }
    }


    public void camera() {
        String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (PermissionUtils.hasPermissions(OnlineVolunteerActivity.this, perms)) {
            startPickPicActivity();
        } else {
            PermissionUtils.requestPermissions(OnlineVolunteerActivity.this, "需要拍照和相册权限", CAMERA_PERIMISSION_CODE, perms);
            camera();
        }
    }

    @AfterPermissionGranted(CAMERA_PERIMISSION_CODE)
    public void startPickPicActivity() {
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        //selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
        boolean showCamera = true;
        int maxNum = 1;
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    postFile(new File(mSelectPath.get(i)));
                }
            }
        }
    }
    private void postFile(File file) {
        final String pic_path = file.getPath();
        String targetPath = FileUtils.getSDCardPath() + file.getName();
        //压缩图片的方法
        final String compressImage = BitmapZip.compressImage(pic_path, targetPath, 90);
        final File compressedPic = new File(compressImage);
        if (compressedPic.exists()) {
            file = compressedPic;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        dialog.show();
        String url = Constant.base_url + "/upload/image";
        Okhttp.postFileParams(url, file, params, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                Toast.makeText(OnlineVolunteerActivity.this, state, Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
            @Override
            public void onResponse(String response, int id) {
                Log.e("TTT上传头像",response);
                dialog.cancel();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String content = jsonObject.optString("data");
                    JSONObject content_json = new JSONObject(content);
                    String face = content_json.optString("path");
                    if (!TextUtils.isEmpty(face)) {
                        get_imageUrl = Constant.base_pic_url + face;
                        initBack(get_imageUrl);
                        new DownloadImageTask().execute(get_imageUrl);
                        PreferencesUtil.putString(OnlineVolunteerActivity.this, Constant.IMAGE, get_imageUrl);
                    } else {
                        Toast.makeText(OnlineVolunteerActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                dialog.cancel();
            }
        });
    }
    private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
        }
    }

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过第二个参数(文件名)来判断，是否本地有此图片
            drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
        } catch (IOException e) {
            Log.e("TTTskythinking", e.getMessage());
        }
        return drawable;
    }
//发送留言消息
    private void initBack(String imageUrl2) {
        String appuserid = PreferencesUtil.getString(OnlineVolunteerActivity.this, Constant.APPUSERID);
        String etVol = etVolunteer.getText().toString().trim();
        String back_url = Constant.base_url + "/commnet/add.do";
        Map<String, String> back_map = new HashMap<>();
        if (TextUtils.isEmpty(etVol)&&imageUrl2 == null) {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        dialog.show();
        back_map.put("content", etVol);
        back_map.put("imageUrl", imageUrl2);//posterId   isUser  fatherId
        back_map.put("avatar", avatar);
        back_map.put("topicID", topicId);
        back_map.put("isUser", 1+"");
        if (!TextUtils.isEmpty(appuserid)) {
            back_map.put("posterId",appuserid);
        }
        if (!TextUtils.isEmpty(fatherId)) {
            back_map.put("fatherId", fatherId);
        } else {
            back_map.put("fatherId", "");
        }
        Okhttp.postString(true, back_url, back_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                Toast.makeText(OnlineVolunteerActivity.this, state, Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }

            @Override
            public void onResponse(String response, int id) {
                etVolunteer.setText("");
                dialog.cancel();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 16 || status == 34) {
                        startActivity(new Intent(OnlineVolunteerActivity.this, LoginActivity.class));
                        return;
                    }
                    initgetVolunteerList();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                Toast.makeText(OnlineVolunteerActivity.this, state, Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
    }
//留言信息列表
    private void initgetVolunteerList() {
        dialog.show();
        String voluntee_list_url = Constant.base_url + "/commnet/list.do";
        Map<String, String> volunteerMap = new HashMap<>();
        Okhttp.postString(true, voluntee_list_url, volunteerMap, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                dialog.cancel();
                Toast.makeText(OnlineVolunteerActivity.this, state, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e("TTTTonLinelist", response);
                dialog.cancel();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 0) {
                        String data = jsonObject.optString("data");
                        JSONObject js = new JSONObject(data);
                        Log.e("TTTTTTT2222", topicId + "==" + content + "=" + imageUrl);
                        String comment = js.optString("commentlist");
                        JSONArray jsonArray = js.optJSONArray("commentlist");



                        JSONObject  jsonComment = new JSONObject();
                        jsonComment.put("topicId", topicId);
                        jsonComment.put("content", content);
                        jsonComment.put("imageUrl", imageUrl);
                        jsonComment.put("avatar", avatar);
                        jsonComment.put("fatherId", "");
                        jsonComment.put("id", "");
                        volunteerlist.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            VolunteerBean volunteerBean = new VolunteerBean();
                            volunteerBean.setAvatar(jsonObject1.optString("avatar"));
                            volunteerBean.setId(jsonObject1.optString("id"));
                            volunteerBean.setContent(jsonObject1.optString("content"));
                            volunteerBean.setTopicID(jsonObject1.optString("topicID"));
                            volunteerBean.setFatherId(jsonObject1.optString("fatherId"));
                            volunteerBean.setImageUrl(jsonObject1.optString("imageUrl"));
                            volunteerBean.setPosterId(jsonObject1.optString("posterId"));
                            volunteerBean.setIsUser(jsonObject1.optInt("isUser"));
                            fatherId = jsonObject1.optString("id");
                            Log.e("TTTTID", fatherId);
                            volunteerlist.add(volunteerBean);
                        }
                   /*     ArrayList<VolunteerBean> volunteerBeen = JsonUtil.json2beans(jsonArray+"", VolunteerBean.class);*/
                        recyclerVolunteer.setLayoutManager(new LinearLayoutManager(OnlineVolunteerActivity.this));
                        //添加分割线
                        //recyclerVolunteer.addItemDecoration(new DividerItemDecoration(OnlineVolunteerActivity.this, DividerItemDecoration.VERTICAL_LIST));
                        VolunteerAdapter volunteerAdapter = new VolunteerAdapter(OnlineVolunteerActivity.this, volunteerlist);
                        recyclerVolunteer.scrollToPosition(volunteerAdapter.getItemCount() - 1);//滑动底部
                        recyclerVolunteer.setAdapter(volunteerAdapter);
                        volunteerAdapter.notifyDataSetChanged();
                        etVolunteer.requestFocus();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                dialog.cancel();
                Toast.makeText(OnlineVolunteerActivity.this, state, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
